import React, { Component } from 'react'
import Footer from './components/Footer'
import Header from './components/Header'
import Main from './components/Main'
import './App.css'

class App extends Component {
  // 初始化状态
  state = {
    list: [
      { id: '001', name: '吃饭', done: true },
      { id: '002', name: '睡觉', done: true },
      { id: '003', name: '打代码', done: false },
      { id: '004', name: '逛街', done: false }
    ],
    active: 'All'
  }

  // 添加todo
  addTodo = (obj) => {
    const { list } = this.state
    const newList = [...list, obj]
    this.setState({ list: newList })
  }

  // 删除todo
  delTodo = (id) => {
    // console.log(id)
    const { list } = this.state
    const newList = list.filter((item) => item.id !== id)
    this.setState({ list: newList })
  }

  // 改变状态
  changeCheck = (id) => {
    // console.log(id)
    const { list } = this.state
    const newList = list.map((item) => {
      if (item.id === id) {
        return { ...item, done: !item.done }
      } else {
        return item
      }
    })
    this.setState({
      list: newList
    })
  }

  // 全选按钮
  allChecked = (done) => {
    const { list } = this.state
    const newList = list.map((item) => {
      return { ...item, done }
    })
    this.setState({ list: newList })
  }

  // 清除所有已完成的todo
  delAllDone = () => {
    const { list } = this.state
    const newTodos = list.filter((item) => !item.done)
    this.setState({ list: newTodos })
  }

  // 切换
  changeActive = (val) => {
    this.setState({
      active: val
    })
  }

  render() {
    const { list, active } = this.state
    return (
      <section className="todoapp">
        <Header addTodo={this.addTodo} />
        <Main
          list={list}
          active={active}
          delTodo={this.delTodo}
          changeCheck={this.changeCheck}
          allChecked={this.allChecked}
        />
        <Footer
          list={list}
          active={active}
          delAllDone={this.delAllDone}
          noDone={this.noDone}
          changeActive={this.changeActive}
        />
      </section>
    )
  }
}

export default App
